package show.me.the.money.servlet;

import java.io.IOException;
import java.io.OutputStream;


import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.*;

import show.me.the.money.resource.CompressScriptFile;
import show.me.the.money.resource.ResourceFile;
import show.me.the.money.resource.ResourceFileController;





public class ScriptLoader extends HttpServlet implements Servlet {;
	private static final long serialVersionUID = -8260076694457868118L;
	private static ResourceFileController resController;
	private static Log log = LogFactory.getLog(ScriptLoader.class);
	
	public void init(ServletConfig oCfg) throws ServletException {
		String sCfgPath = oCfg.getInitParameter("basePath");
		String sBasePath = oCfg.getServletContext().getRealPath(sCfgPath);
		resController = new ResourceFileController(sBasePath);
		ResourceFile.setContentTypeMapping("js", "application/x-javascript;charset=gb2312");
		log.info("inited..");
	}
	
	public static ResourceFile getScriptResourceFile(String clsName){
		ResourceFile resFile;
		try {
			resFile = resController.getResourceFile(clsName, CompressScriptFile.class);
			return resFile;
		} 
		catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}

	public void doGet(HttpServletRequest oRequest, HttpServletResponse oResponse){
		String sClsName =  getClsName(oRequest.getRequestURI());
		if(!StringUtils.isEmpty(sClsName)){
			if(sClsName.endsWith(".jsc")){
				sClsName = sClsName.replace(".jsc", ".js");
			}
		}
		try {
			ResourceFile oResFile = getScriptResourceFile(sClsName);
			if(oResFile != null && oResFile.exists()){
				oResponse.addHeader("content-type", oResFile.getContentType());
				oResFile.writeToStream(oResponse.getOutputStream());
			}
			else{
				oResponse.setStatus(404);
				log.fatal("["+ sClsName + "] script file not found.");
			}
		} catch (Exception e) {
			oResponse.setStatus(500);
			log.fatal(e);
		}
		
	}
	
	public void doPost(HttpServletRequest oRequest, HttpServletResponse oResponse){
		String reqStr = oRequest.getHeader("classes");
		if(reqStr == null){
			log.error("classes request header missing.");
			oResponse.setStatus(500);
			return;
		}
		String[] classes = reqStr.split("&_");
		OutputStream outs = null;
		try {
			outs = oResponse.getOutputStream();
		} catch (IOException e) {
			log.error("get outputStream falied:" + e.toString());
			oResponse.setStatus(500);
		}
		if(null == outs){
			return;
		}
		oResponse.addHeader("content-type", ResourceFile.getContentTypeMapping("js"));
		int n = classes.length;
		for(int i = 0; i < n; i ++){
			try {
				String sClsName = classes[i] + ".js";
				ResourceFile oResFile = getScriptResourceFile(sClsName);
				if(oResFile.exists()){
					outs.write(10);
					oResFile.writeToStream(outs,false);
				}
				else{
					log.fatal("["+ sClsName + "] script file not found.");
				}
			} 
			catch (Exception e) {
				log.error(e.toString());
				oResponse.setStatus(500);
			}
			
		}
		try {
			outs.close();
		} 
		catch (IOException e) {
			log.fatal("write script file to stream error:" + e.getMessage());
		}
		
	}
	
	private String getClsName(String ReqUrl){
		int p = ReqUrl.lastIndexOf("/");
        String sCls = "";
        if(p > -1){
			sCls = ReqUrl.substring(p+1);
        }
        return sCls;
	}
	
}